<template>
  <div class="content-box">
    <e-heading style="margin: 0 0 20px;">{{isPreview ? '赛程预览': '赛程'}}</e-heading>
    <e-sliderbox
      :value="activeGroup"
      :list="groupList"
      :slides="8"
      @change="handleChange">
      <template slot-scope="scope">
        {{scope.groupName| groupName}}
      </template>
    </e-sliderbox>

    <DateSlider style="margin:20px 0 50px;"
      v-model="activeDate" 
      :list="dateList" 
      @change="handleCheck">
    </DateSlider>

    <div v-if="gameList.length">
      <place-group :list="placeList" v-model="selectedPlaceIdx" @change="handleSelect"/>
      <!--预览-->
      <ul class="match-list preview" v-show="isPreview">
        <li v-for="(item,$index) in gameList" class="match-item  clearfix" v-bind:class="{odd:$index%2==0}"
          :key="item.dateTime"
          :id="item.id">
          <el-row>
            <el-col :span="4">
              <p class="horizon small">{{ new Date(item.startTime).format("yyyy-MM-dd hh:mm") }}</p>
            </el-col>
            <el-col :span="4">
              <p class="horizon small" v-if="item.gradeRemark.indexOf('第') > -1">
                {{Number(item.gradePage)| NumberToArab}} 第{{item.grade}}轮
              </p>
              <p class="horizon small" v-else>
               {{item.gradeRemark}}
              </p>
            </el-col>
            <el-col :span="5" :offset="1">
              <div class="fl host-team">
                <span class="team-name hidden">
                  {{item.hostUserName + (item.hostUserName2 ? '&'+item.hostUserName2: '') || (item.hostUserId =='pending' ? '待定': (item.hostUserId|| '待定'))}}                    
                </span>
              </div>
              <div class="fl no-margin">
                <e-img-match :alt="item.hostUserName" :src="item.hostIconUrl || '/static/images/default-logo.png'"/>
              </div>
            </el-col>
            <el-col :span="1" >
              <p class="match-vers horizon">vs</p>
            </el-col>
            <el-col :span="5" :offset="1">
              <div class="fl no-margin">
                <e-img-match :alt="item.guestUserName" :src="item.guestIconUrl || '/static/images/default-logo.png'"/>
              </div>
              <div class="fl guest-team">
                <span class="team-name hidden">
                  {{item.guestUserName +(item.guestUserName2? '&'+item.guestUserName2:'') || (item.guestUserId== 'pending'?'待定': (item.guestUserId|| '待定'))}}
                </span>
              </div>
            </el-col>
          </el-row>
        </li>
      </ul>
      <!--编辑-->
      <ul class="match-list small" v-show="!isPreview">
        <li v-for="(item,$index) in gameList" class="match-item  clearfix" 
            v-bind:class="{odd:$index%2==0}"
            :key="item.id"
            :id="item.id">
            <el-row>
              <el-col :span="4" class="match-date">
                <p class="small">{{new Date(item.startTime).format("yyyy-MM-dd hh:mm")}}</p>
                <template v-if="item.gradeRemark.indexOf('第') > -1">
                  <p class="small">{{Number(item.gradePage)| NumberToArab}} 第{{item.grade}}轮</p>
                </template>
                <template v-else>
                  <p class="small">{{item.gradeRemark}}</p>
                </template>
              </el-col>
              <el-col :span="4">
                <div class="team">
                  <div class="host tm-name">
                    <p v-if="item.hostUserName || item.hostUserId">
                      {{(item.hostUserName+ (item.hostUserName2?'&'+item.hostUserName2: '')) || (item.hostUserId !== 'pending' ? item.hostUserId:'待定') }}
                    </p>
                    <p v-else>待定</p>
                    <template v-if="item.status==6 && Number(item.homeScore)==0">
                      <div class="giveup">已弃权</div>
                    </template>                          
                    <el-button type="link" 
                      v-if="item.guestUserName && item.hostUserName && (!item.homeScore) && ![4,5,6].includes(item.status)"
                      @click="giveUp($event, item,'host')">弃权</el-button>
                  </div>
                </div>
              </el-col>       
              <el-col :span="2" class="logo">
                  <e-img-match :src="item.hostIconUrl"/>
              </el-col>           
              <el-col :span="3">
                <div class="match-vs">
                  <p v-if="!item.homeScore && (!item.guestScore)" class="match-vers">vs</p>
                  <p v-if="item.end|| item.guestScore" class="match-vers">{{item.homeScore}}:{{item.guestScore}}</p>
                  <el-button style="line-height:19px;" type="link"  
                    v-if="!item.homeScore && ![4,5,6].includes(item.status) && item.hostUserName && item.guestUserName"
                    @click="openScore(item)">录入比分</el-button>
                </div>
              </el-col>
              <el-col :span="2"  class="logo">
                  <e-img-match :src="item.guestIconUrl" />
              </el-col>
              <el-col :span="4">
                <div class="team">
                  <div class="tm-name">
                    <p v-if="item.guestUserName || item.guestUserId">
                      {{(item.guestUserName + (item.guestUserName2? '&'+item.guestUserName2: '')) || (item.guestUserId !== 'pending' ? item.guestUserId: '待定')}}
                    </p>
                    <p v-else>待定</p>
                    <template v-if="item.status==6 && Number(item.guestScore)==0">
                      <div class="giveup">已弃权</div>
                    </template> 
                    <el-button 
                      v-if="item.guestUserName && item.hostUserName && (!item.homeScore) && ![4,5,6].includes(item.status)" 
                      type="link"  @click="giveUp($event, item,'guest')">弃权</el-button>
                  </div>
                </div>
              </el-col>
              <el-col :span="5">
                <!--status: 0、初始化（2轮以上赛事默认使用），1、待比赛，2、已结束，3、延迟比赛，4、取消比赛，5轮空,6：弃权-->
                <div v-if="item.status!==4 &&  item.status!==6 && item.status!=2">
                  <el-button v-show="!item.homeScore" size="mini" @click="editGame(item)">编辑比赛</el-button>
                  <el-button v-show="!item.homeScore && (['半决赛','决赛','三、四名决赛','1/4决赛'].indexOf(item.gradeRemark)== -1)" 
                      size="mini" @click="showCancel(item)">取消比赛</el-button>                                      
                </div>
                <div v-if="item.status==4">
                  <span  class="canceled">已取消</span>
                </div>
                <div v-if="item.status==6">
                  <template v-if="item.remark">
                    <span class="canceled">{{item.remark}}</span>
                  </template>
                  <template v-else>
                    <span class="canceled" v-if="item.homeScore==0">主队弃权</span>
                    <span class="canceled" v-if="item.guestScore==0">客队弃权</span>
                  </template>                      
                </div>
                <div v-if="item.status==2 && isGroup">
                  <el-button size="small" @click="lookDetails(item)">
                    查看比分详情
                  </el-button>
                </div>
                <div v-if="item.status==2 && hasScoreDetail">
                  <el-button size="small" @click="getScoreDetail(item)">
                    查看比分详情
                  </el-button>
                </div>
              </el-col>
            </el-row>                
        </li>
      </ul>
    </div>

    <div v-else>没有比赛</div>

    <div class="button-box" v-if="isPreview">            
      <el-button type="primary" @click="$router.go(-1)">返回编辑</el-button>
      <el-button @click="generate()">生成赛程</el-button>
    </div>
    <div class="button-box" v-else>
      <el-button v-if="IsCupSeperate && !isKnockoutStage" :disabled="!canBuildCheckTable" @click="dVisible=true">创建签表</el-button>
      <el-button type="primary" @click="exportExcel()">导出Excel</el-button>
    </div>
    <!--淘汰赛编辑阶段才展示签表-->
    <div v-if="!isPreview && (isKnockoutStage || !IsCupSeperate)">
      <e-heading class="title" grade="1">淘汰赛晋级表 
        <small v-if="playRound>2" v-bind:class="{active:isSemifinal==false}" @click="isSemifinal = false">大签表</small> 
        <small v-bind:class="{active:isSemifinal==true}"  
          @click="isSemifinal = true"
          v-if="playRound==7 || playRound==6 || playRound==5 || playRound==2" >
          半决赛
        </small>
      </e-heading>
      
      <template v-if="bigTableVisible && !isSemifinal">
        <check-table
          :dataList="dataList"
          :roundList="roundList"
          :zoneNumber="zoneNumber"
          :areaIndex="areaIndex"
          :isCup="true"
          @active="handleActive">
        </check-table>
      </template>

      <template v-else>      
        <semifinal  
          :isPreview="true"
          :dataList="semiList"
          @scoreWrite="openScore">
        </semifinal>
      </template>
    </div>
    

    <!--录入大比分弹框-->
    <el-dialog
      class="score-dialog"
      :visible.sync="scoreVisible"
      :title="'请输入最终比分'"
      @close="closeScore()">
      <div class="relative">
        <div style="margin-bottom:10px;">
          <label class="game-name hidden">{{game.hostUserName + (game.hostUserName2 ? '&' + game.hostUserName2 : '')}}</label>
          <el-input class="score-input" v-model.trim="homeScore" :maxlength="3">
            <template slot="append">分</template>
          </el-input>
        </div>
        <div>
          <label class="game-name hidden">{{game.guestUserName + (game.guestUserName2 ? '&' + game.guestUserName2 : '')}}</label>
          <el-input class="score-input" v-model.trim="guestScore" :maxlength="3">
            <template slot="append">分</template>
          </el-input>
        </div>
        <el-popover
          class="pop-over"  ref="popover5"
          placement="top"   width="200"
          v-model="popVisible">
          <p class="warnning">比分一经录入不能再次修改，是否确认录入？</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="popVisible = false">取消</el-button>
            <el-button type="primary" size="mini" @click="scoreWrite()">确定</el-button>
          </div>        
        </el-popover>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeScore()">取 消</el-button>
        <el-button type="primary" @click="checkPoint()">确 定</el-button>
      </span>  
    </el-dialog>

    <!-- 取消比赛弹框 --> 
    <cancel-game-dialog
      v-show="cancelVisible"
      :visible.sync="cancelVisible"
      @close="hideMessageBox"
      @cancel="hideMessageBox"
      @confirm="cancelGame">
    </cancel-game-dialog>

    <!--团体赛小比分弹框-->
    <score-group
      v-if="scoreGroupVisible"
      :visible="scoreGroupVisible"
      :data="match"
      :detail="scoreGroup"
      :isRead="isRead"
      @close="scoreGroupVisible=false"
      @score="handleScore">
    </score-group>
    
    <!--小比分弹框--> 
    <score-dialog
      v-if="scoreDetailsVisible"
      :isRead="isReadScore"
      :visible="scoreDetailsVisible"
      :data="scoreDetail"
      :result="scoreResult"
      :host="game.hostUserName + (game.hostUserName2 ? '&'+game.hostUserName2 : '')"
      :guest="game.guestUserName + (game.guestUserName2 ? '&'+game.guestUserName2 : '')"
      @score="score"
      @close="scoreDetailsVisible=false">
    </score-dialog>

    <!--签表弹框-->
    <el-dialog
      v-if="IsCupSeperate"
      class="tiny-dialog"  :top="'35%'"  :title="'温馨提示'"
      :visible.sync="dVisible"
      @close="dVisible = false">
      <p>请选择创建签表方式</p>
      <span slot="footer" class="dialog-footer">
        <router-link :to="{
          path: '/race/detail/manage/createsigntable',
          query: Object.assign({isedit:'no'},  this.$route.query) 
        }">
          <el-button>手动录入</el-button>
        </router-link>
        <el-button type="primary" @click="autoGenerate()">自动生成</el-button>
      </span>
    </el-dialog>
  </div>  
</template>

<script>
import Api from 'api/race'
import ESliderbox from '@e-ui/Sliderbox'
import CheckTable from './components/CheckTable'
import Semifinal from './components/Semifinal'
import DateSlider from './components/DateSlider'
import PlaceGroup from './components/PlaceGroup'
import CancelGameDialog from './components/CancelGameDialog.vue'
import ScoreDialog from './components/ScoreDialog'
import {knockout, cloneObj, filterPlace, downloadFile, sortByTime, groupRaceFormat, seqList, matchFormat, IsScoreDetail, IsCupSeperate} from 'utils' // eslint-disable-line
import ScoreGroup from './components/ScoreGroup'
import {mapGetters} from 'vuex'
export default {
  components: {
    Semifinal,
    CheckTable,
    DateSlider,
    PlaceGroup,
    CancelGameDialog,
    ESliderbox,
    ScoreGroup,
    ScoreDialog
  },
  computed: {
    ...mapGetters({
      race_detail: 'race_detail'
    }),
    isPreview () { // 是否预览
      return this.$route.path.indexOf('schedulepre') > -1
    },
    groupGrade () { // 小组赛轮数
      let n = 0
      for (let d in this.firstGroup.schedules) {
        let day = this.firstGroup.schedules[d]
        if (day.length) {
          day.forEach(g => {
            if (g.grade > n) {
              n = g.grade
            }
          })
        }
      }
      return n
    },
    isGroup () { // 是团体赛
      return [300501, 300401, 300301].indexOf(this.race_detail.matchType) > -1
    },
    hasScoreDetail () { // 录入小比分
      return IsScoreDetail(this.race_detail)
    },
    IsCupSeperate () { // 是杯赛分离模式
      return IsCupSeperate(this.race_detail)
    }
  },
  created () {
    this.getScheduleInfo()
    if (!this.isPreview) {
      if (!this.isKnockoutStage) {
        this.canCheckTable()
      }
      this.getDrawData()
    }
  },
  watch: {
    // '$route': 'handleRouteChange'
  },
  data () {
    return {
      dVisible: false,
      canBuildCheckTable: false,
      isKnockoutStage: 0, // 判断是小组赛阶段还是淘汰赛阶段 0：小组赛，1：淘汰赛
      scoreDetailsVisible: false, // 小比分弹框
      scoreResult: {},
      scoreDetail: {},
      activeDateIndex: 0,
      activeGroupIndex: 0,
      selectedPlaceIdx: 0,
      bigTableVisible: false,
      isSemifinal: false, // 是否为半决赛
      roundList: [], // 轮次标题列表
      semiList: [], // 半决赛列表
      areaIndex: 0,
      playRound: 2, // 淘汰赛轮数
      scoreVisible: false,
      cancelVisible: false,
      popVisible: false,
      homeScore: '',
      guestScore: '',
      activeGroup: {},
      groupList: [],
      firstGroup: {},
      activeDate: {},
      dataList: [], // 签表
      dateList: [], // 日期列表
      placeList: [], // 场地列表
      gameList: [], // 比赛列表
      canceledGame: {},
      cancelCase: 0, // 取消原因
      game: {},
      checkTableList: [],
      isRead: false,
      scoreGroup: {},
      scoreGroupVisible: false,
      match: {}
    }
  },
  methods: {
    resetData (list, isResetPlace) {
      if (!list) {
        this.placeList = []
        this.gameList = []
      } else {
        this.placeList = filterPlace(list)
        if (isResetPlace) {
          this.selectedPlaceIdx = 0
        }
        this.gameList = sortByTime(this.placeList[this.selectedPlaceIdx].data, 'startTime')
      }
    },
    // 获取赛程信息
    getScheduleInfo (isInit) {
      Api.getCupScheduleInfo({
        matchId: this.$route.query.id,
        isPreview: this.IsCupSeperate && this.isPreview ? 1 : undefined
      }).then((res) => {
        let result = []
        this.firstGroup = res.data['A']
        if (res.data['all']) {
          result.push({
            groupName: 'all',
            nav: res.data['all'].nav,
            schedules: res.data['all'].schedules
          })
        }
        for (let x in res.data) {
          if (x != 'knockout' && x != 'all') { // eslint-disable-line
            result.push({
              groupName: x,
              nav: res.data[x].nav,
              schedules: res.data[x].schedules
            })
          }
        }
        if (res.data['knockout']) {
          this.isKnockoutStage = 1
          result.push({
            groupName: 'knockout',
            nav: res.data['knockout'].nav,
            schedules: res.data['knockout'].schedules
          })
        }
        this.groupList = result
        this.activeGroup = this.groupList[this.activeGroupIndex]
        this.dateList = this.activeGroup.nav
        this.activeDate = this.dateList[this.activeDateIndex] ? this.dateList[this.activeDateIndex] : this.dateList[0]
        let gameList = this.activeGroup.schedules[this.activeDate.scheduleDate]
        this.resetData(gameList)
      })
    },
    // 分组点击事件
    handleChange (group) {
      this.activeGroup = group
      this.activeGroupIndex = this.groupList.indexOf(group)
      this.dateList = group.nav
      this.activeDate = this.dateList[0]
      this.activeDateIndex = 0
      let gameList = this.activeGroup.schedules[this.activeDate.scheduleDate]
      this.resetData(gameList, 1)
    },
    // 日期点击事件
    handleCheck (date) {
      this.activeDate = date
      this.activeDateIndex = this.dateList.indexOf(date)
      let gameList = this.activeGroup.schedules[date.scheduleDate]
      this.resetData(gameList, 1)
    },
    // 场地点击事件
    handleSelect (i) {
      let index = typeof i === 'number' ? i : Number(i.placeNumber)
      index = index > this.placeList.length - 1 ? 0 : index
      this.gameList = sortByTime(this.placeList[index].data, 'startTime')
    },
    hideMessageBox () {
      this.cancelVisible = false
    },
    // 取消比赛
    cancelGame (obj) {
      Api.matchCancel({
        id: this.canceledGame.id,
        cancleCase: obj.cancelCase,
        remark: obj.remark
      }, {context: this}).then((res) => {
        this.canceledGame.status = 4
        this.$message({
          type: 'success',
          message: '取消成功!'
        })
        this.hideMessageBox()
        let ind = this.dateList.indexOf(this.activeDate)
        if (ind >= 0) {
          this.dateList[ind].matchNumber--
        }
        this.getDrawData()
        this.shouldGetAllowCheck()
      }).catch((err) => {
        this.$message({
          type: 'warning',
          message: err.msg
        })
        this.hideMessageBox()
      })
    },
    // 弹出取消比赛弹框
    showCancel (item) {
      this.canceledGame = item
      this.cancelVisible = true
    },
    // 进入编辑比赛页面
    editGame (item) {
      if (!item.hostUserName) {
        item.hostUserName = '待定'
      }
      if (!item.guestUserName) {
        item.guestUserName = '待定'
      }
      this.$store.commit('MATCH_DETAIL', item)
      this.$router.push({
        path: '/race/detail/manage/matchedit',
        query: {
          id: this.$route.query.id,
          gameId: item.id,
          isRun: this.$route.query.isRun,
          tasktype: this.$route.query.tasktype
        }
      })
    },
    closeScore () {
      this.scoreVisible = false
      this.homeScore = ''
      this.guestScore = ''
      this.popVisible = false
    },
    // 打开录入比分弹框
    openScore (item) {
      if (this.isGroup) {
        if (!item.sequence) {
          Api.getSequence({
            matchId: this.$route.query.id,
            matchScheduleId: item.id
          }).then((res) => {
            item.sequence = seqList(res.data)
            this.match = Object.assign({}, {id: item.id, sequence: item.sequence, hostTeam: item.hostUserName, guestTeam: item.guestUserName}, groupRaceFormat(this.race_detail))
            this.scoreGroupVisible = true
          })
        } else {
          this.match = Object.assign({}, {id: item.id, sequence: item.sequence, hostTeam: item.hostUserName, guestTeam: item.guestUserName}, groupRaceFormat(this.race_detail))
          this.scoreGroupVisible = true
        }
        this.isRead = false
      } else {
        if (this.hasScoreDetail) {
          this.scoreDetail = matchFormat(this.race_detail)
          this.scoreDetailsVisible = true
          this.isReadScore = false
        } else {
          this.scoreVisible = true
        }
      }
      this.game = item
    },
    checkPoint () {
      if ((Number.isInteger(parseInt(this.homeScore))) && (Number.isInteger(parseInt(this.guestScore))) &&
        parseInt(this.homeScore) >= 0 && parseInt(this.guestScore) >= 0) {
        this.popVisible = true
      } else {
        this.$message({
          type: 'error',
          message: '比分请输入非负整数'
        })
        return false
      }
    },
    // 录入比分
    scoreWrite () {
      if ((Number.isInteger(parseInt(this.homeScore))) && (Number.isInteger(parseInt(this.guestScore))) &&
        parseInt(this.homeScore) >= 0 && parseInt(this.guestScore) >= 0) {
        if ((Number(this.game.gradePage) < 0 || Number(this.game.gradePage) > 32) && parseInt(this.homeScore) === parseInt(this.guestScore)) { // 淘汰赛
          this.$message({
            type: 'error',
            message: '比分请输入非负数，且不能为平局'
          })
          return false
        }
        Api.scoreWrite({
          id: this.game.id,
          hostScores: Number(this.homeScore),
          guestScores: Number(this.guestScore),
          cupScoreVO: []
        }, {context: event.target}).then((res) => {
          this.game.homeScore = this.homeScore
          this.game.guestScore = this.guestScore
          this.getScheduleInfo()
          if (Number(this.game.gradePage) < 1 || Number(this.game.gradePage) > 32) { // 淘汰赛
            this.getDrawData()
          }
          this.shouldGetAllowCheck()
          this.closeScore()
        }).catch((err) => {
          console.log(err.msg)
          this.popVisible = false
        })
      } else {
        this.$message({
          type: 'error',
          message: '比分请输入非负整数'
        })
        return false
      }
    },
    // 比赛弃权
    giveUp (event, item, team) {
      let isHost = team === 'host' ? 1 : 0
      let text = ''
      if (isHost) {
        text = '主队：' + item.hostUserName + (item.hostUserName2 ? '&' + item.hostUserName2 : '')
      } else {
        text = '客队：' + item.guestUserName + (item.guestUserName2 ? '&' + item.guestUserName2 : '')
      }
      this.$confirm('确认 ' + text + ' 弃权?', '提示', {
        type: 'warning'
      }).then(() => {
        Api.matchGiveup({
          id: item.id,
          hostUserId: item.hostUserId,
          guestUserId: item.guestUserId,
          status: 6, // 4：取消比赛，5：轮空，6：弃权
          result: isHost ? 3 : 4 // 3：主队弃权，4：客队弃权
        }, {context: event.target}).then((res) => {
          item.end = 1
          item.status = 6
          item.homeScore = res.data.hostScore
          item.guestScore = res.data.guestScore
          if (item.gradeRemark.includes('决赛') || this.groupGrade === item.grade) { // 淘汰赛或者小组赛最后一轮
            this.getScheduleInfo()
            this.getDrawData()
          }
          this.shouldGetAllowCheck()
        }).catch((err) => {
          this.$message({
            type: 'warning',
            message: err.msg
          })
        })
      }).catch(() => {
      })
    },
    // 生成赛程
    generate () {
      this.$confirm('确定要生成赛程？', '提示', {
        type: 'warning'
      }).then(() => {
        Api.generateSchedule({matchId: this.$route.query.id}, {context: this}).then((res) => {
          this.$router.push({ // 杯赛
            path: '/race/detail/manage/schedulecup',
            query: this.$route.query
          })
          this.getDrawData()
          this.canCheckTable()
          if (this.IsCupSeperate) {
            this.getScheduleInfo()
            this.$store.commit('RACE_HAS_SCHEDULE', false)
            this.$store.commit('RACE_SCHEDULE', {})
          }
        }).catch((err) => {
          this.$message({
            type: 'warn',
            message: err.msg
          })
        })
      })
    },
    // 获取签表数据
    getDrawData () {
      Api.getDrawData({matchId: this.$route.query.id}).then((res) => {
        this.zoneNumber = res.data.length
        if (this.zoneNumber > 1) { // 有分区,球队>=32
          this.checkTableList = res.data
          if (res.data[4]) {
            this.playRound = res.data[4].grades[1].grade
            this.semiList = res.data[4].grades
          }
        } else {
          this.playRound = res.data[0].grades.length
          if (this.playRound === 2) { // 4支
            this.semiList = res.data[0].grades
            this.isSemifinal = true
          }
          if (this.playRound === 3) { // 8支
            this.isSemifinal = false
          }
          if (this.playRound === 4) { // 16支
            this.semiList = res.data[0].grades.filter(item => {
              return item.grade > 2
            })
          }
        }
        this.bigTableVisible = this.playRound > 2
        this.dataList = res.data[this.areaIndex].grades
        this.handleSort()
        this.calcRound()
      })
    },
    handleSort () {
      this.dataList.sort(function (a, b) {
        return a.grade - b.grade
      })
    },
    // 计算有多少轮
    calcRound () {
      this.roundList = knockout(this.playRound)
    },
    // 选中分区tab事件
    handleActive (index) {
      this.areaIndex = index
      this.dataList = this.checkTableList[index].grades
      this.handleSort()
    },
    // 导出赛程
    exportExcel () {
      let url = '/api/match/schedule/export/schedulePrevInfo?matchId=' + this.$route.query.id
      let _this = this
      downloadFile(url, this.race_detail.matchName + '.xls', function (blob) {
        _this.$message({
          message: '下载出错，请稍后再试',
          type: 'warning'
        })
      })
    },
    // 录入团体比分
    handleScore (data) {
      Api.score(data).then((res) => {
        this.scoreGroupVisible = false
        this.getScheduleInfo()
        if (this.groupGrade === this.game.grade || Number(this.game.gradePage) < 1 || Number(this.game.gradePage) > 32) { // 淘汰赛
          this.getDrawData()
        }
        this.shouldGetAllowCheck()
      })
    },
    // 查看团体比分详情
    lookDetails (item) {
      this.isRead = true
      if (item.scoreList) {
        this.scoreGroup = item.scoreList
        this.scoreGroupVisible = true
      } else {
        Api.getGroupScore({
          matchScheduleId: item.id
        }).then((res) => {
          let sg = {
            hostTeam: item.hostUserName,
            guestTeam: item.guestUserName,
            hostScore: res.data.hostScore,
            guestScore: res.data.guestScore,
            scoreList: res.data.mssvo
          }
          item.scoreList = Object.assign({}, groupRaceFormat(this.race_detail), sg)
          this.scoreGroup = item.scoreList
          this.scoreGroupVisible = true
        })
      }
    },
    // 录入小比分
    score (val) {
      Api.scoreDetail({
        id: this.game.id,
        hostScore: val.hostScore,
        guestScore: val.guestScore,
        hostUserId: this.game.hostUserId,
        guestUserId: this.game.guestUserId,
        roundType: String(this.race_detail.formatNumberType),
        scoreGameVO: val.scoreGameVO
      }, {context: event.target}).then((res) => {
        this.game.homeScore = this.homeScore
        this.game.guestScore = this.guestScore
        this.getScheduleInfo()
        if (this.groupGrade === this.game.grade || Number(this.game.gradePage) < 1 || Number(this.game.gradePage) > 32) { // 淘汰赛
          this.getDrawData()
        }
        this.shouldGetAllowCheck()
        this.scoreDetailsVisible = false
      }).catch((err) => {
        console.log(err.msg)
      })
    },
    // 查看个人赛小比分
    getScoreDetail (item) {
      this.isReadScore = true
      if (item.scoreList) {
        this.scoreResult = item.scoreList
        this.scoreDetailsVisible = true
      } else {
        Api.getScoreDetail({
          matchScheduleId: item.id
        }).then((res) => {
          let game = matchFormat(this.race_detail)
          item.scoreList = {
            roundType: game.roundType,
            scoreList: res.data.smallScoreScanVO || [],
            hostUserName: item.hostUserName + (item.hostUserName2 ? '&' + item.hostUserName2 : ''),
            guestUserName: item.guestUserName + (item.guestUserName2 ? '&' + item.guestUserName2 : ''),
            hostScore: res.data.hostScore,
            guestScore: res.data.guestScore,
            dish: game.dish
          }
          this.scoreResult = item.scoreList
          this.scoreDetailsVisible = true
        })
      }
    },
    // 是否可以生成签表
    canCheckTable () {
      Api.canCheckTable({
        matchId: this.$route.query.id
      }).then((res) => {
        this.canBuildCheckTable = res.data
      })
    },
    shouldGetAllowCheck () {
      // 分离模式(小组赛)录完比分，弃权，取消比赛 等操作后查询是否可以生成签表
      if (!this.isKnockoutStage && this.IsCupSeperate && !this.canBuildCheckTable) {
        this.canCheckTable()
      }
    },
    autoGenerate () {
      Api.CupBuildCheckTable({matchId: this.$route.query.id}, {successMsg: '生成成功'}).then((res) => {
        this.$router.push({
          path: '/race/detail/manage/checktable',
          query: this.$route.query
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/scheduleCup.scss';
@import '../../styles/knockout.scss';   
.preview{
  font-size: 12px;
}
.team-name{
  width:70px;
  line-height: 38px;
}
.horizon{
  line-height: 38px!important;
}
.no-margin{
  img{
    margin-left: 0;
    margin-right: 0;
  }
}
.host-team{
  margin-right:20px;
}
.guest-team{
  margin-left: 20px;
}
.champion:after{
  content:url('/static/images/champion.png');
}
</style>
<style lang="scss">
.pop-over{
  .el-popover{
    right: 20px;
    top: 68px;
    display: block;
  }
  .warnning{
    line-height: 20px;
    margin-bottom: 5px;
    font-size: 14px;
  }
}
.score-dialog{
  .el-dialog{
    width: 420px;
    .el-dialog__body{
      text-align:center;
    }
  }
}
.tiny-dialog .el-dialog{
  width: 420px!important;
}
.score-input{
  display: inline-block;
}
</style>
